<?PHP
#
#   FILE:  RecordImageCollage.php
#
#   Part of the Metavus digital collections platform
#   Copyright 2021-2022 Edward Almasy and Internet Scout Research Group
#   http://metavus.net
#
# @scout:phpstan

namespace Metavus\Plugins\Collage;

use Metavus\Record;
use ScoutLib\ApplicationFramework;
use ScoutLib\PluginManager;

/**
 * Generate HTML for an image collage
 */
class RecordImageCollage
{
    private static $CollageCount = 0;

    private $RecordIds;

    /**
     * Constructor, takes in array of Records and prepares for display before saving in field
     * @param array $RecordIds Record IDs to display in collage
     */
    public function __construct(array $RecordIds)
    {
        # calculate how many tiles we need
        $Plugin = (PluginManager::getInstance())->getPlugin("Collage");
        $NumberOfImages = $Plugin->getNumberOfImages();

        # if record list is too short for a full collage, extend by merging with self
        # use copy of array to avoid massive arrays for small tile widths
        $InitialRecords = $RecordIds;
        while ((count($RecordIds) > 0)
                && (count($RecordIds) < $NumberOfImages)) {
            $RecordIds = array_merge(
                $RecordIds,
                $InitialRecords
            );
        }
        $this->RecordIds = $RecordIds;
        self::$CollageCount++;
    }

    # ---- PUBLIC INTERFACE --------------------------------------------------

    /**
     * Generate HTML for an image collage
     * @return string html representing collage - empty string if $this->RecordIds is empty
     */
    public function getHtml()
    {
        $GLOBALS["AF"]->requireUIFile("RecordImageCollage.js");
        $Plugin = $GLOBALS["G_PluginManager"]->getPlugin("Collage");

        # if we weren't given records, don't try to get a collage
        if (count($this->RecordIds) == 0) {
            return "";
        }

        shuffle($this->RecordIds);

        # calculate height for collage assuming square tiles
        $TileWidth = $Plugin->configSetting("TileWidth");
        $CollageHeight = $Plugin->configSetting("NumRows") * $TileWidth;

        # generate/return actual html
        $CollageHtml = "<div class=\"col mv-p-collage-wrapper\" style=\"height:"
            .$CollageHeight."px;\"><div class=\"mv-p-collage\">";
        foreach ($this->RecordIds as $Id) {
            $Record = new Record($Id);
            $CollageHtml .= self::getHtmlForRecord($Record);
        }
        return $CollageHtml."</div>".((self::$CollageCount == 1) ?
            "</div><div id=\"mv-rollover-dialog\" style=\"display: none;\" ".
            "data-tile-width=\"".$TileWidth."\" ".
            "data-dialog-width=\"".$Plugin->configSetting("DialogWidth")."\" ".
            "data-expected-vp-width=\"".$Plugin->configSetting("MaxExpectedViewportWidth")."\" ".
            "data-num-rows=\"".$Plugin->configSetting("NumRows")."\">".
            "<p><a class=\"mv-url\"></a><br>".
            "<a class=\"mv-fullrecord\">(More Info)</a></p>".
            "<p class=\"mv-description\"></p></div>" : "");
    }

    # ---- PRIVATE INTERFACE -------------------------------------------------

    /**
     * Get html for one record (image and dialogue data)
     * @param Record $Record record to get html for
     * @return string html div with image and data for popup
     */
    private static function getHtmlForRecord(Record $Record)
    {
        $Screenshot = $Record->getMapped("Screenshot", true);
        if (is_null($Screenshot) || count($Screenshot) == 0) {
            return "";
        }
        $Screenshot = reset($Screenshot);
        $Plugin = $GLOBALS["G_PluginManager"]->getPlugin("Collage");

        # entity-encoded text in data attributes is correctly handled by jquery-ui
        $Title = $Record->getMapped("Title");
        $Description = $Record->getMapped("Description");
        $Url = $Record->getMapped("Url");
        $FullRecordUrl = $Record->getViewPageUrl();
        $GoToUrl = ApplicationFramework::baseUrl().
            ApplicationFramework::getInstance()
            ->getCleanRelativeUrlForPath(
                "index.php?P=GoTo"
                ."&ID=".$Record->id()
                ."&MF=".$Record->getSchema()->stdNameToFieldMapping("Url")
            );

        return "<div class=\"mv-p-collage-tile\"".
        " title=\"".htmlspecialchars($Title)." [click for detail]\"".
        " data-title=\"".htmlspecialchars($Title)."\"".
        " data-description=\"".htmlspecialchars($Description)."\"".
        " data-url=\"".htmlspecialchars($Url)."\"".
        " data-fullrecord=\"".htmlspecialchars($FullRecordUrl)."\"".
        " data-goto=\"".htmlspecialchars($GoToUrl)."\"".
        "><img src=\"".$Screenshot->url("mv-image-thumbnail")."\" alt=\"\" ".
        "style=\"width:".($Plugin->configSetting("TileWidth"))."px; ".
        "height:".($Plugin->configSetting("TileWidth"))."px;\" /></div>";
    }
}
